package com.niiwoo.civet.trade.service.local.common;

import com.niiwoo.civet.base.enums.ChannelCodeEnum;
import com.niiwoo.civet.base.enums.DeviceTypeEnum;
import com.niiwoo.civet.base.enums.FeeTypeEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectLoanDeviceInfo;
import com.niiwoo.civet.trade.dao.mapper.ProjectBorrowerPlanDetailMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectLoanDeviceInfoMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dao.mapper.TradeConfigMapperExt;
import com.niiwoo.civet.trade.enums.ProjectFromSourceEnum;
import com.niiwoo.civet.trade.enums.ProjectStatusEnum;
import com.niiwoo.civet.trade.enums.ProjectSubStatusEnum;
import com.niiwoo.civet.trade.enums.ProjectTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 标的公共服务
 *
 * @author: LiJian
 * @Date:2017/11/15
 * @update jiabo 2018/5/1
 */
@Slf4j
@Service
public class ProjectCommonService {

    @Autowired
    private ProjectMapperExt projectMapperExt;

    @Autowired
    private ProjectBorrowerPlanDetailMapperExt projectBorrowerPlanDetailMapper;

    @Autowired
    private ProjectLoanDeviceInfoMapperExt projectLoanDeviceInfoMapperExt;
    @Autowired
    private TradeConfigMapperExt tradeConfigMapperExt;

    /**
     * 根据用户ID、标的状态、子状态统计标的数目
     *
     * @param userId
     * @param statusList
     * @param subStatusList
     * @return
     */
    public int statisticsProjectCountByStatus(String userId, List<Byte> statusList, List<Integer> subStatusList) {
        return projectMapperExt.statisticsProjectCountByStatus(userId, statusList, subStatusList);
    }

    /**
     * 根据用户ID、单个状态统计用户标的数
     *
     * @param userId
     * @param status    状态
     * @param subStatus 子状态
     * @return
     */
    public int statisticsProjectCountBySingleStatus(String userId, Byte status, Integer subStatus) {
        return projectMapperExt.statisticsProjectCountBySingleStatus(userId, status, subStatus);
    }

    /**
     * 统计用户当前逾期标的数量
     *
     * @param userId
     * @return
     */
    public int statisticsUserOverdueNow(String userId) {
        return projectMapperExt.selectOverdueCount(userId);
    }

    /**
     * 统计超过一定逾期天数标的
     *
     * @param userId
     * @param day
     * @return
     */
    public int statisticsUserOverdueExceedDay(String userId, Integer day) {
        return projectMapperExt.statisticsUserOverdueExceedDay(userId, day);
    }

    /**
     * 查询在上线前或上线后逾期超过一定天数的用户的标的数量
     *
     * @param userId
     * @param exceedDays
     * @param publishTime
     * @param isBeforePublish
     * @return
     */
    //    public int selectOverdueInCondition(String userId, Integer exceedDays, String publishTime, int isBeforePublish) {
    //
    //        //正常还款数量
    //        int normalRepaymentCount = projectBorrowerPlanMapperExt.selectOverdueInConditionForNormalRepayment(userId, publishTime,isBeforePublish);
    //        //逾期还款数量
    //        int overdueRepaymentCount = projectBorrowerPlanMapperExt.selectOverdueInConditionForOverdueRepayment(userId, exceedDays,publishTime,isBeforePublish);
    //        //未还款
    //        int nonRepaymentCount = projectBorrowerPlanMapperExt.selectOverdueInConditionForNonRepayment(userId, exceedDays,publishTime,isBeforePublish);
    //
    //        return normalRepaymentCount+overdueRepaymentCount+nonRepaymentCount;
    //    }

    /**
     * 查询标的信息
     *
     * @param projectId
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Project queryProjectBasicInfo(Long projectId) {
        return projectMapperExt.selectByPrimaryKey(projectId);
    }

    /**
     * 查询标的信息
     *
     * @param userId
     * @param projectId
     * @return
     */
    public Project selectByUserIdAndProjectId(String userId, Long projectId) {
        return projectMapperExt.selectByUserIdAndProjectId(userId, projectId);
    }

    /**
     * 获取标的列表
     *
     * @param projectIdSet
     * @return
     */
    public List<Project> queryProjectListByProjectIdSet(Set<Long> projectIdSet) {
        if (null == projectIdSet || projectIdSet.isEmpty()) {
            return new ArrayList<>();
        }
        return projectMapperExt.queryProjectListByProjectIds(Arrays.asList(projectIdSet.toArray(new Long[projectIdSet.size()])));
    }

    /**
     * 更新标的信息
     *
     * @param project
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateByPrimaryKeySelective(Project project) {
        projectMapperExt.updateByPrimaryKeySelective(project);
    }

    /**
     * 查询标的设备信息
     *
     * @param projectId
     * @return
     */
    public ProjectLoanDeviceInfo queryLoanDeviceInfo(Long projectId) {
        return projectLoanDeviceInfoMapperExt.selectByPrimaryKey(projectId);
    }

    /**
     * 查询在审核状态中的某一时间区间的标列表
     *
     * @return
     */
    public List<Project> queryAuthNotifyAuditProjectList(Date endDate) {
        return projectMapperExt.queryAuthNotifyAuditProjectList(endDate);
    }

    /**
     * 从主表查询查询标的信息
     *
     * @param userId
     * @param projectId
     * @return
     */
    @Transactional
    public Project selectByUserIdAndProjectIdFromMaster(String userId, Long projectId) {
        return projectMapperExt.selectByUserIdAndProjectId(userId, projectId);
    }

    /**
     * 获取借款已使用额度
     *
     * @param userId
     * @return
     */
    public BigDecimal getLoanUsedAmout(String userId) {
        List<Byte> statusList = new ArrayList<>();
        // 只统计审核中、募集中 的借款金额
        statusList.add(ProjectStatusEnum.CHECKING.getStatus());
        statusList.add(ProjectStatusEnum.COLLECTING.getStatus());
        BigDecimal usdAmout = projectMapperExt.statisticsLoanAmountByStatus(userId, statusList, null, null);

        log.info("getLoanUsedAmout.userId={},usdAmout1={}", userId, usdAmout);

        usdAmout = (usdAmout == null ? BigDecimal.ZERO : usdAmout);
        // 减去已退回、审核待确认标的金额
        List<Integer> subStatusList = Arrays.asList(
                ProjectSubStatusEnum.CHECKING_BACK.getSubStatus(),
                ProjectSubStatusEnum.CHECKING_BACK_PHONEOPERATOR_TIMEOUT.getSubStatus(),
                ProjectSubStatusEnum.CHECKING_BACK_ADDRESSLIST_TIMEOUT.getSubStatus(),
                ProjectSubStatusEnum.CHECKING_FOR_CONFIRM.getSubStatus()
        );
        BigDecimal backAmount = projectMapperExt.statisticsLoanAmountByStatus(userId, null, subStatusList, null);

        log.info("getLoanUsedAmout.userId={},backAmount={}", userId, backAmount);

        backAmount = (backAmount == null ? BigDecimal.ZERO : backAmount);

        log.info("getLoanUsedAmout.userId={},");

        // 查询未还本金总额
        BigDecimal noRepayedRefundedCapital = projectBorrowerPlanDetailMapper.countToPayMoneyByUserIdAndFeeType(userId, FeeTypeEnum.CAPITAL.getValue());

        log.info("getLoanUsedAmout.userId={},noRepayedRefundedCapital={}", userId, noRepayedRefundedCapital);

        noRepayedRefundedCapital = (noRepayedRefundedCapital == null ? BigDecimal.ZERO : noRepayedRefundedCapital);

        usdAmout = usdAmout.subtract(backAmount).add(noRepayedRefundedCapital);

        return usdAmout;
    }

    public ProjectLoanDeviceInfo queryUserLastLoanDeviceInfo(String userId) {
        return projectLoanDeviceInfoMapperExt.queryUserLastLoanDeviceInfo(userId);
    }

    /**
     * 从主表查询标的设备信息
     *
     * @param projectId
     * @return
     */
    @Transactional
    public ProjectLoanDeviceInfo queryLoanDeviceInfoFromMaster(Long projectId) {
        return projectLoanDeviceInfoMapperExt.selectByPrimaryKey(projectId);
    }

    /**
     * 是否卡牛标的
     *
     * @param project
     * @return
     */
    public Boolean isCardNiuProject(Project project) {
        if (project != null && ProjectFromSourceEnum.CARD_NIU.getType().equals(project.getFromSource())
                && ProjectTypeEnum.CARD_NIU_LOAN.getValue() == project.getType()) {
            return true;
        }
        return false;
    }

    /**
     * 是否融360标的
     *
     * @param project
     * @return
     */
    public Boolean isR360Project(Project project) {
        if (project != null && ProjectFromSourceEnum.R360.getType().equals(project.getFromSource())) {
            return true;
        }
        return false;
    }

    /**
     * 是否考拉理财标的
     *
     * @param project
     * @return
     */
    public Boolean isKaolaProject(Project project) {
        if (project != null && ChannelCodeEnum.KAOLA.getChanelCode().equals(project.getChannelCode())) {
            return true;
        }
        return false;
    }

	/**
     * 获取APP下载地址
     * 1:安卓，2：IOS
     * @return
     */
	public List<String> getAppDownloadUrl() {
		List<String> urls = new ArrayList<>();
		urls.add(tradeConfigMapperExt.selectTradeConfigByKey(DeviceTypeEnum.ANDROID.getDownloadUrlKey()));
		urls.add(tradeConfigMapperExt.selectTradeConfigByKey(DeviceTypeEnum.IOS.getDownloadUrlKey()));
		return urls;
	}
}
